/*
 * @Author: your name
 * @Date: 2021-06-14 22:09:35
 * @LastEditTime: 2021-06-14 22:38:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hexo_blog\\192.168.2.100\jzijin\signal_thread.c
 */
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

#define MAX_THREAD 5
static pid_t g_main_pid = 0;
static pthread_t pid_arr[MAX_THREAD];

static void sig_handler(int signum)
{
    printf("get signum %d, the thread_id is %lu\n", signum, pthread_self());
}

void *send_sig_func(void *)
{
    while (1)
    {
        /* send to all thread_group */
        // kill(g_main_pid, SIGUSR1);

        pthread_kill(pid_arr[3], SIGUSR1);
        sleep(1);
    }
}

void *do_nothing(void *)
{
    while(1)
    {
        sleep(1);
    }
}

int main(void)
{
    struct sigaction act;
    sigset_t block_set;

    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    act.sa_handler = sig_handler;
    sigaction(SIGUSR1, &act, NULL);

    g_main_pid = getpid();
    printf("g_main_pid = %lu\n", g_main_pid);
    printf("thread_id = %lu\n", pthread_self());


    int i;
    int ret;
    for (i = 0; i < MAX_THREAD - 1; ++i)
    {
        ret = pthread_create(&pid_arr[i], NULL, do_nothing, NULL);
        printf("pid_arr[%d] = %lu\n", i, pid_arr[i]);
    }

    ret = pthread_create(&pid_arr[MAX_THREAD - 1], NULL, send_sig_func, NULL);
    printf("pid_arr[%d] = %lu\n", MAX_THREAD - 1, pid_arr[MAX_THREAD - 1]);
    
    sigemptyset(&block_set);
    sigaddset(&block_set, SIGUSR1);

    sigprocmask(SIG_BLOCK, &block_set, NULL);

    for (i = 0; i < MAX_THREAD; ++i)
    {
        pthread_join(pid_arr[i], NULL);
    }

    return 0;
}